--
-- Author: yawei.zhu
-- Date: 2018-09-26 15:14:28
--
-- WorldBossView
--

local AvatarFactory = app:getClass("AvatarFactory")

local WorldBossRender = import(".renders.WorldBossRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.WorldBossScene

function ClassRef:init()
	self._ui.Button_close:addClickEventListener(function()
		self:closeView()
	end)

	self._ui["Panel_r/btn_go"]:addClickEventListener(function()
		--直接开始挑战，只限队长可以操作
        local teamModel = app:getInst("TeamModel")
        if not teamModel:hasTeam() then
			display.pushToast( L("findOrCreateTeam") )
			--executeFunc(self._onOperate, "openTeamview")
			return
		end
		if not teamModel:isLeader() then
			display.pushToast( L("cannotChallengeWorldBoss") )
			return
		end
        --判断队伍中是否有不满足世界BOSS开启等级的队员
        local minLv = teamModel:getMemberMinLv()
        local openLv = GD:getWorldBossOpenLevel()
		if minLv < openLv then
			display.pushToast(string.format(L("membersLvIsNotEnough"), openLv))
			return
		end 
        executeFunc(self._onOperate, "shownReadyUIOrTeamSettingUI")
	end)
	self._ui["Panel_r/Panel_bom_1/btn_go"]:addClickEventListener(function()
		-- TODO 追踪
		executeFunc(self._onOperate, "onTrackWorldBoss")
        self:closeView()
	end)
	self._ui["Panel_r/Panel_bom_1/btn_team"]:addClickEventListener(function()
		executeFunc(self._onOperate, "openWorldBossTeam")
	end)
	self._ui["Panel_r/Panel_bom_2/btn_team"]:addClickEventListener(function()
		executeFunc(self._onOperate, "openWorldBossTeam")
	end)

    if app:getInst("TeamModel"):isMyTeam() then
        self._ui["Panel_r/btn_go"]:setBright(true)
    else
        self._ui["Panel_r/btn_go"]:setBright(false)
    end

	local rankRenders = {}
	for i = 1, 3 do
		local node = self._ui["Panel_r/node_"..i]
		local render = WorldBossRender.create(node)
		render:onBtnClick(function()
			executeFunc(self._onOperate, "reqCurRank", i)
		end)
		table.insert(rankRenders, render)
	end
	self._rankRenders = rankRenders

	self._panelRightBossDB = self._ui.Panel_1 -- boss龙骨动画区
	self._dragonWidth, self._dragonHeight = self._panelRightBossDB:getContentSize2()
end

function ClassRef:_tick(dt)
	local serverTime = app.session:getServerTime()
	local remainedTime = math.floor(self._endTime - serverTime)
	if remainedTime <= 0 then -- 活动结束
		self:hideBottomBtn()
		self._ui["Panel_r/Panel_bom_3"]:setVisible(true)
		self._ui.time:setString(L("worldBossIsOver"))
		self:removeScheduler()
	else
		if self._worldBossStatusData and self._worldBossStatusData.open then -- 活动开了才显示倒计时
			local time = TimeUtil.secondsToTime(remainedTime)
			self._ui.time:setString(string.format(L("worldBossLeftTimes"), time))
		else
			self._ui.time:setVisible(false)
		end
	end
end

function ClassRef:updateView(entrance, bossInfo)
	self._endTime = GD:getWolrdBossEndTime()

	for i = 1, 3 do
		self._rankRenders[i]:setData({index = i, bossInfo = bossInfo})
	end

	-- boss
	local bossConfig = GD:queryNpc(bossInfo.bossId)
	self._ui.title:setString(L(bossConfig.name))

	-- 显示boss
	self:setBoss(bossInfo.bossId)

	-- 底部按钮
	self:hideBottomBtn()
	if bossInfo.killed then
		self._ui.Panel_bom_2:setVisible(true)
		self._ui.img_over:setVisible(true)
	else
		if entrance == 1 then
			self._ui.Panel_bom_1:setVisible(true)
		else
			self._ui["Panel_r/btn_go"]:setVisible(true)
		end
	end
	self._worldBossStatusData = app:getInst("BossModel"):getWorldBossStatusData()
	-- 添加定时器
	self:removeScheduler()
	self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
	self:_tick()
end

function ClassRef:updateViewBox(bossInfo)
    for i = 1, 3 do
		self._rankRenders[i]:setData({index = i, bossInfo = bossInfo})
	end
end

function ClassRef:setBoss(bossId)
	AvatarFactory.preloadNpcById(bossId, function()
		local function createNpc()
			-- boss dragonBones
			local bossArmatrueNode = AvatarFactory.createNpcById(bossId)
			if bossArmatrueNode then
				self._panelRightBossDB:removeAllChildren()
				self._panelRightBossDB:addChild(bossArmatrueNode)
				local actionName = "mapidle"
				if bossArmatrueNode:hasAnimation(actionName) then
					bossArmatrueNode:getAnimation():play(actionName)
				end

				local box = bossArmatrueNode:getBoundingBox()
				local scale = math.min( self._dragonWidth/box.width, self._dragonHeight/box.height )
				bossArmatrueNode:setScale( scale )

				local box2 = bossArmatrueNode:getBoundingBox()
				local pos = self._panelRightBossDB:convertToNodeSpace(cc.p(box2.x + box2.width/2, box2.y))
				bossArmatrueNode:setPositionX( self._dragonWidth/2 - pos.x )
			end
		end

		if not cc.isDead(self) then
			scheduler.newCron(createNpc, 0.05)
		end
	end )
end

-- 隐藏底部按钮
function ClassRef:hideBottomBtn()
	self._ui["Panel_r/btn_go"]:setVisible(false)
	self._ui["Panel_r/Panel_bom_1"]:setVisible(false)
	self._ui["Panel_r/Panel_bom_2"]:setVisible(false)
	self._ui["Panel_r/Panel_bom_3"]:setVisible(false)
end


function ClassRef:onExit()
	self:removeScheduler()
end

function ClassRef:removeScheduler()
	if self._cronsIdx then
		scheduler.cancelCron(self._cronsIdx)
		self._cronsIdx = nil
	end
end

return ClassRef
